/**
 * @author harry
 * @date 2022/2/27/11:28
 */

package com.serviceOrchestration.controller;

import com.serviceOrchestration.annotation.RoleRestriction;
import com.serviceOrchestration.exception.LoginException;
import com.serviceOrchestration.pojo.ReturnData;
import com.serviceOrchestration.service.LoginService;
import com.serviceOrchestration.util.Role;
import com.serviceOrchestration.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    private final LoginService loginService;

    @Autowired
    public AdminController(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping("/login")
    public ReturnData<?> login(@RequestBody Map<String, String> params, HttpServletResponse response) throws LoginException {
        String id = params.get("id");
        String password = params.get("password");
        Map<String, String> ret = loginService.adminLogin(id, password);
        String token = ret.get("token");
        String role = ret.get("role");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.AUTHORIZATION);
        response.setHeader(HttpHeaders.AUTHORIZATION, token);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.AUTHORIZATION);
        return ReturnData.ok(role);
    }

    @RoleRestriction({Role.ADM, Role.SUP})
    @GetMapping("/logout")
    public ReturnData<?> logout(@RequestAttribute("token") String token) {
        if (loginService.logout(token)) {
            return ReturnData.ok();
        }
        return ReturnData.error(StatusCode.SERVER_ERROR);
    }
}
